#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-10-7'
# code is far away from bugs with the god animal protecting ~
"""
from django.conf import settings
from django_redis import get_redis_connection
from rest_framework import serializers

import constants
from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from oauth.utils import check_save_user_token
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """
    添加用户浏览历史序列化器
    """
    sku_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    def validate_sku_id(self, value):
        """
        检验sku_id是否存在
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """
        保存
        """
        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']

        redis_conn = get_redis_connection("history")
        pl = redis_conn.pipeline()

        # 移除已经存在的本商品浏览记录
        pl.lrem("history_%s" % user_id, 0, sku_id)
        # 添加新的浏览记录
        pl.lpush("history_%s" % user_id, sku_id)
        # 只保存最多5条记录
        pl.ltrim("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)

        pl.execute()

        return validated_data


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """
    class Meta:
        model = User
        fields = ('email',)
        extra_kwargs = {'email': {'required': True}}

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = email
        instance.save()

        serializer = TJS(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
        data = {'user_id': instance.id, 'email': instance.email}
        token = serializer.dumps(data).decode()
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token

        send_verify_email.delay(email,verify_url)

        return instance


# class EmailVerifySerializer(serializers.ModelSerializer):
#     """
#     email verification serializer
#     """
#     token = serializers.CharField(label="用户令牌", write_only=True)
#
#     class Meta:
#         model = User
#         fields = ('token',)
#
#     def update(self, instance, validated_data):
#         token = validated_data.get('token')
#
#         if not token:
#             raise serializers.ValidationError('token丢失')
#
#         data = check_save_user_token(token)
#
#         user_id = data.get('user_id')
#         email = data.get('email')
#
#         if not user_id or not email:
#             raise serializers.ValidationError('token解析错误')
#
#         try:
#             user = User.objects.get(id=user_id)
#         except Exception as e:
#             raise serializers.ValidationError('token中的用户不存在')
#
#         user.email_active = True
#         user.save()
#
#         return instance
